<template>
  <el-dialog title="分配角色" :visible.sync="dialogFormVisible">
    <el-form :model="userData">
      <el-form-item label="" :label-width="formLabelWidth">
        <el-select
          v-model="userData.roleIdList"
          multiple
          placeholder="请选择角色"
        >
          <el-option
            v-for="role in allRoles"
            :label="role.name"
            :value="role.id"
            :key="role.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getUserRoles, allocateUserRoles } from '@/api/user'
export default {
  name: 'AllocRole',
  data () {
    return {
      dialogFormVisible: false,
      allRoles: [],
      userData: {
        userId: 0,
        roleIdList: []
      },
      formLabelWidth: '120px'
    }
  },
  methods: {
    onSave () {
      allocateUserRoles(this.userData).then((res) => {
        if (res.data.code === '000000') {
          this.$message.success('分配角色成功')
          this.dialogFormVisible = false
        } else {
          this.$message.error('分配角色失败')
        }
      })
    },
    showAndInit (user) {
      this.dialogFormVisible = true
      getUserRoles(user.id).then((res) => {
        if (res.data.code === '000000') {
          this.allRoles = res.data.data
          this.userData.userId = user.id
          this.userData.roleIdList = res.data.data
            .filter((role) => role.hasPermission)
            .map((role) => role.id)
        } else {
          this.$message.error('获取列表失败')
        }
      })
    }
  }
}
</script>
